package com.gitee.zeric.codec.parser;

import cn.hutool.core.util.StrUtil;
import com.gitee.zeric.codec.check.CodeUniqueCheck;
import com.gitee.zeric.codec.generaters.CodeGenerater;
import com.gitee.zeric.codec.model.RuleModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * 缓存编码生成器
 * @author zj
 * @date 2021/12/14
 */
@Slf4j
public class CachedCodeRuleParser extends DefaultCodeRuleParser implements InitializingBean {

    private final static ExecutorService executorService = Executors.newScheduledThreadPool(20);

    public CachedCodeRuleParser(CodeUniqueCheck codeUniqueCheck, RedisTemplate redisTemplate, StringRedisTemplate stringRedisTemplate,String zcodeprefix) {
        super(codeUniqueCheck,redisTemplate,stringRedisTemplate,zcodeprefix);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        // initialize RingBuffer & RingBufferPaddingExecutor
//        Set<String> keys = this.getRedisTemplate().keys(CodeGenerater.REDIS_DB_CODE_RULE_PREFIX + "*");
//        //立即执行，并且每5秒执行一次
//        initCodeBuffer(keys);
//        LOGGER.info("Initialized RingBuffer successfully.");
    }

    /**
     * Initialize CodeBuffer & RingBufferPaddingExecutor
     */
    private void initCodeBuffer(Set<String> ruleCodeKeys) {
        for (String ruleCode : ruleCodeKeys) {
            RuleModel ruleGenerate = (RuleModel) this.getRedisTemplate().opsForValue().get(ruleCode);
            if(ruleGenerate==null){return;}
            if (StrUtil.equals(ruleGenerate.getRuleType(), "1")) {
                executorService.submit(() -> {
                    String key = "zcloud_cache:" + ruleGenerate.getRuleCode();
                    Long size = this.getRedisTemplate().hasKey(key) ? this.getRedisTemplate().opsForSet().size(key) : 0;
                    long defaultSize = 1024;
                    if (size < 1024) {
                        defaultSize = defaultSize - size;
                        List<String> codes = this.batchUniqParse(ruleGenerate.getRuleCode(), Long.valueOf(defaultSize).intValue(),15);
                        this.getRedisTemplate().opsForSet().add(key, codes);
                    }
                });
            }
        }
    }

//    @Override
//    public List<String> batchTake(String ruleCode, int size) {
//        return this.getRedisTemplate().opsForSet().pop("jfdcloud_cache:" + ruleCode, size);
//    }
}
